package com.lj.back.manage.scaffold.module.sys.aop;

import com.lj.back.manage.scaffold.common.constant.Constant;
import com.lj.back.manage.scaffold.common.enums.StatusEnum;
import com.lj.back.manage.scaffold.common.util.CommonUtil;
import com.lj.back.manage.scaffold.common.util.HttpRequestUtil;
import com.lj.back.manage.scaffold.module.sys.DO.SysLogDO;
import com.lj.back.manage.scaffold.module.sys.annotation.SysLog;
import com.lj.back.manage.scaffold.module.sys.dao.SysLogDao;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * 记录系统日志aop
 * @author lv
 * @version 1.0.0
 */
@Aspect
@Component
@Slf4j
@AllArgsConstructor
public class SysLogAop {

    private final HttpServletRequest request;

    private final SysLogDao sysLogDao;

    @Pointcut("@annotation(log)")
    public void pointcut(SysLog log) {}

    @Around("pointcut(sysLog)")
    public Object around(ProceedingJoinPoint joinPoint, SysLog sysLog) throws Throwable {
        String status = StatusEnum.SUCCESS.getCode();
        Object proceed = null;
        long startTime = System.currentTimeMillis();
        try{
            proceed = joinPoint.proceed();
        }catch (Exception e){
            log.error("记录业务日志异常",e);
            status = StatusEnum.FAIL.getCode();
            return CommonUtil.getExceptionResult(e);
        }finally {
            long endTime = System.currentTimeMillis();
            //记录日志
            saveLog(joinPoint,sysLog,(endTime-startTime),status);
        }
        return proceed;
    }

    public void saveLog(ProceedingJoinPoint joinPoint, SysLog log, long times, String status){
        SysLogDO sysLogDO = new SysLogDO();
        sysLogDO.setUserName("admin");
        sysLogDO.setOperateType(log.operateType().getCode());
        sysLogDO.setOperation(log.value());
        sysLogDO.setIp(HttpRequestUtil.getRequestIp(request));
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        //请求的参数
        Object[] args = joinPoint.getArgs();
        //请求的方法名
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = method.getName();
        sysLogDO.setMethod(className+Constant.SEPARATOR_BEAN_NAME+methodName);
        sysLogDO.setParams(CommonUtil.jsonFormat(CommonUtil.GSON.toJson(args)));
        sysLogDO.setTimes(times);
        sysLogDO.setStatus(status);
        sysLogDao.insert(sysLogDO);
    }
}
